package com.imut.lagain.config;

import com.imut.lagain.interceptor.AccessLogInterceptor;
import com.imut.lagain.interceptor.DataOperationLogInterceptor;
import com.imut.lagain.interceptor.PerformanceInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 * 用于配置拦截器、静态资源等
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private static final Logger log = LoggerFactory.getLogger(WebConfig.class);

    private final AccessLogInterceptor accessLogInterceptor;
    private final DataOperationLogInterceptor dataOperationLogInterceptor;
    private final PerformanceInterceptor performanceInterceptor;

    public WebConfig(AccessLogInterceptor accessLogInterceptor,
                     DataOperationLogInterceptor dataOperationLogInterceptor,
                     PerformanceInterceptor performanceInterceptor) {
        this.accessLogInterceptor = accessLogInterceptor;
        this.dataOperationLogInterceptor = dataOperationLogInterceptor;
        this.performanceInterceptor = performanceInterceptor;
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("注册访问日志拦截器");
        registry.addInterceptor(accessLogInterceptor)
                .addPathPatterns("/api/**") // 只拦截API请求
                .excludePathPatterns(
                    "/api/auth/wx-login", // 排除微信登录接口
                    "/api/auth/verify-token", // 排除令牌验证接口
                    "/api/capsules/share/**", // 排除分享接口（可能不需要认证）
                    "/api/actuator/**" // 排除监控端点
                )
                .order(1); // 设置优先级

        log.info("注册数据操作日志拦截器");
        registry.addInterceptor(dataOperationLogInterceptor)
                .addPathPatterns("/api/**") // 只拦截API请求
                .excludePathPatterns(
                    "/api/auth/**", // 排除认证相关接口
                    "/api/logs/**", // 排除日志查询接口
                    "/api/actuator/**" // 排除监控端点
                )
                .order(3); // 设置优先级

        log.info("注册性能监控拦截器");
        registry.addInterceptor(performanceInterceptor)
                .addPathPatterns("/api/**") // 只拦截API请求
                .excludePathPatterns(
                    "/api/auth/**", // 排除认证相关接口
                    "/api/logs/**", // 排除日志查询接口
                    "/api/actuator/**" // 排除监控端点
                )
                .order(2); // 设置优先级
    }

    /**
     * 配置RestTemplate
     * @return RestTemplate实例
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
